#!/bin/bash
# name: upload.sh
# discription:
#   upload video to webdav(nutstore)
# Usage:
#   > nohup upload.sh "$1" "$2" &
# varibles:
#   $1: file name, or directory name
#   $2: output name, used for tarball
# Attention:
#   1. use as `nohup upload.sh $1 $2 &`
#   2. make sure no nohup.out exist in working directory.
#   3. have installed cadaver(webdav client)

# set bash behavior: if error in pipe ,return code is non-zero.
set -o pipefail

########################################################################
# Step1: compress(tar) and split(split) it into smaller files(<500M)
# webdav(nutstore) doesn't allow uploading files bigger than 500M.
TarballPrefix="$(date +%h%d%H%M)."
tar -jcvf - "$1" | split -b 495M -d -a 2 - "$TarballPrefix"

# Check Point: if error,stop script.
if [ $? != 0 ]
then
    echo "Error: Something wrong with Compress or Split"
    exit
fi
echo "Check: Compress and Split success!"


# make md5
if test -d "$1"
then
    md5sum "$TarballPrefix"* > verify.md5
else
    md5sum "$1" > verify.md5
fi
#########################################################################
# Step2: use cadaver to upload to webdav
echo "cadaver running,uploading..."
echo "more info in cadaver.log"
cadaver https://dav.jianguoyun.com/dav/BigShare <<EOF > cadaver.log
mput $TarballPrefix*
put verify.md5
ls
exit
EOF
if [ $? != 0 ]
then
    echo "Error: cadaver Failed to upload"
else
    echo "Check: cadaver exit!"
fi

# Check Point: Check whether all files has been uploaded.
# get total number of files splited (Local files)
NosFile=$(ls . | grep -c "$TarballPrefix")
# get total number of uploaded files from nohup.out(cadaver's command `ls` >> nohup)(Webdav files)
NosWebFile=$(cat cadaver.log | grep -A 100 "Listing collection" |grep -c "$TarballPrefix" )

echo "Local file number: $NosFile"
echo "Webdav file number: $NosWebFile"
if [ $NosFile = $NosWebFile ]
then
    echo "Check: cadaver upload success!"
    echo "Finish: upload $1"
    
    # remove temp files(produced by split) to save disk space
    if rm "./$TarballPrefix"* verify.md5 cadaver.log
    then
        echo "Temp files removed!"
        echo "All work finished!"
    fi
else
    echo "Check: cadaver upload failed!"
    echo "UnFinished: Error happend while uploading!"
fi
